#include "common.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <time.h>
#include <sys/time.h>

int main()
{
	int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(sock_fd < 0)
		err_sys("socket error\n");

	struct sockaddr_in my_addr;
	bzero(&my_addr, sizeof(my_addr));
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(9999);
	my_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int ret = bind(sock_fd, (struct sockaddr *)&my_addr, sizeof(my_addr));
	if(ret != 0)
		err_sys("bind error\n");

	ret = listen(sock_fd, 5);
	if(ret != 0)
		err_sys("listen error\n");

	printf("listening ...\n");

	while(1)
	{
		struct sockaddr_in client_addr;
		char client_ip[INET_ADDRSTRLEN] = {0};
		socklen_t client_len = sizeof(client_addr);
		int conn_fd;

		conn_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &client_len);
		if(conn_fd < 0)
			err_sys("accept error\n");

		inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
		printf("Client IP = %s\nPort = %d\n", client_ip, ntohs(client_addr.sin_port));

		char recv_buf[1024] = "";
		while(recv(conn_fd, recv_buf, 1024, 0) > 0)
		{
			printf("\nrecv data : %s\n", recv_buf);
			//if(strncmp(recv_buf, "time\n", strlen("time\n")) == 0)
			if(strstr(recv_buf, "time\n") != NULL)
			{
				printf("find\n");
				time_t now;
				time(&now);
				//struct tm *time_tmp = localtime(&now);

				char *time_buf = NULL;
				time_buf = (char *)malloc(sizeof(char) * 512);
				//time_buf = asctime(time_tmp);
				time_buf = ctime(&now);

				send(conn_fd, time_buf, strlen(time_buf), 0);
			}
		}

		close(conn_fd);
		printf("Client closed!\n");
	}

	close(sock_fd);
	return 0;
}
